import MD5 from './md5';
import { TipError } from './tip';
import { basePath } from '@router/config';
import { platformTruth } from './environment';
import { closeWxWindow } from './oauth/wechat';
import QRCode from 'qrcode';
import dayjs from 'dayjs';
import convert from 'color-convert';

/**
 * 16进制增加透明度
 * @param {String} hexColor 16进制颜色值
 * @param {Number} opcity 透明度
 */
export const colorAddOpcity = (hexColor, opcity) => {
    const reg = /#/g;
    const _hex = hexColor.replace(reg, '');
    const val = convert.hex.rgb(_hex);
    return `rgb(${val.join(', ')}, ${opcity})`;
};
/**
 * 页面重定向到给定地址
 * @param {String} path 页面跳转路径
 * @param {Object} param 跳转需要添加的参数
 */
export const redirectTo = (path, param = {}) => {
    let query = '';
    for (let key in param) {
        query += `${key}=${param[key]}&`;
    }
    window.location.href = `${basePath}/${path}${query ? '?' + query : ''}`;
};

/**
 * 给地址添加参数
 * @param {String} url url地址
 * @param {Object} param 参数对象
 */
export const urlAddParam = (url, param = {}) => {
    let query = '';
    for (let key in param) {
        query += `${key}=${param[key]}&`;
    }
    return `${url}?${query}`;
};

/**
 * 替换页面到给定地址
 * @param {String} path 地址
 * @param {Object} param 页面带的参数
 */
export const repalceTo = (path, param = {}) => {
    let query = '';
    for (let key in param) {
        query += `${key}=${param[key]}&`;
    }
    window.location.replace(`${basePath}/${path}${query ? '?' + query : ''}`);
};

/**
 * 浏览器返回方法
 */
export const navigateBack = () => {
    window.history.go(-1);
};

/**
 * 浏览器前进给定步长
 * @param {Number} num 前进步长，默认：1
 */
export const navigateForward = (num = 1) => {
    window.history(num);
};

/**
 * 获取 url 参数
 * @param {String} name 参数名
 */
export const getUrlParam = (name, url) => {
    const uri = url ? new URL(decodeURIComponent(url)) : window.location;
    let search = decodeURIComponent(uri.search);
    search = search.substring(1, search.length);
    const arr = search.split('&');
    let result = '';
    for (let i = 0; i < arr.length; i++) {
        const _name = arr[i].split('=')[0];
        if (_name === name) {
            result = arr[i].split('=')[1];
            break;
        }
    }
    return result;
};

/**
 * 获取当前url的参数对象
 */
export const getUrlAllParam = () => {
    let search = decodeURIComponent(window.location.search);
    search = search.substring(1, search.length);
    const arr = search.split('&');
    let result = {};
    for (let i = 0; i < arr.length; i++) {
        const name = arr[i].split('=')[0];
        const value = arr[i].split('=')[1];
        result[name] = value;
    }
    return result;
};

/**
 * 设置页面title
 * @param {String} title 页面名称
 */
export const setTitle = (title) => {
    const { isAlipay } = platformTruth();
    if (isAlipay) {
        window.AlipayJSBridge.call('setTitle', {
            title,
        });
    } else {
        document.title = title;
    }
};

/**
 * 随机生成一个给定长度的字符串
 * @param {Number} length 随机字符的长度
 */
export const getRandomString = length => {
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let temp = '';
    for (let i = 0; i < length; i++) {
        temp += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return temp;
};

/**
 * 生成接口需要的签名
 * @param {Object} params 参数
 */
export const createSign = (params) => {
    const sign = [];
    Object.keys(params).sort().forEach(key => {
        sign.push(`${key}=${params[key]}`);
    });
    return MD5(sign.join('&') + '3000KR_MD5_KEY');
};

/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} name 图片名
 */
export const createImageSrc = (name) => {
    return `https://bgp.bucket.biling.club/${name}?imageView2/2/w/180/q/90`;
};
/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} name 图片名
 */
export const createBigImageSrc = (name) => {
    return `https://bgp.bucket.biling.club/${name}?imageView2/1/w/750/h/750/q/100`;
};
/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} name 图片名
 */
export const createBaseImageSrc = (name) => {
    return `https://bgp.bucket.biling.club/${name}`;
};

/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} url 图片地址
 */
export const createShopImageSrc = (url) => {
    if (!url) {
        return 'http://bgp.bucket.biling.club/shop-default-pic.png?imageView2/1/w/400/h/400/q/100';
    }
    return `${url}?imageView2/1/w/400/h/400/q/100`;
};

/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} name 图片名
 */
export const createShopAdImageSrc = (name) => {
    if (!name) {
        return 'https://bgp.bucket.biling.club/shop-default-pic.png?imageView2/1/w/345/h/140/q/100';
    }
    return `https://bgp.bucket.biling.club/${name}?imageView2/1/w/345/h/140/q/100`;
};

/**
 * 生成七牛cdn的图片服务器地址
 * @param {String} name 图片名
 */
export const createShopDetailImageSrc = (name) => {
    if (!name) {
        return 'https://bgp.bucket.biling.club/shop-default-pic.png?imageView2/1/w/375/h/375/q/100';
    }
    return `https://bgp.bucket.biling.club/${name}?imageView2/1/w/375/h/375/q/100`;
};

/**
 * 生成七牛cdn的视频服务器地址
 * @param {String} name 图片名
 */
export const createShopDetailVideoSrc = (name) => {
    if (!name) {
        return '';
    }
    return `https://bgp.bucket.biling.club/${name}`;
};

/**
 * 处理营销错误
 * @param {Function} fun 回调函数
 */
export const dealMktError = async (fun) => {
    try {
        return fun && await fun();
    } catch (error) {
        TipError(error.message);
        return false;
    }
};

/**
 * 添加返回关闭事件
 */
export const addBackClose = () => {
    var state = {
        title: 'title',
        url: '#',
    };
    window.history.pushState(state, null, '#');
    window.addEventListener('popstate', function(event) {
        closeWxWindow();
    });
};

/**
 * 生成图片二维码，用于使用长按识别
 * @param {String} val 需要生成二维码的内容
 */
export const createImageQrcode = (val) => {
    return new Promise((resolve, reject) => {
        QRCode.toDataURL(val, {
            errorCorrectionLevel: 'L',
            margin: 1,
            width: 220,
        }, (err, url) => {
            if (err) reject(err);
            resolve(url);
        });
    });
};

/**
 * 生成canvas二维码
 * @param {HTMLElement} canvas html canvas 元素
 * @param {String} val 需要生成二维码的内容
 */
export const createCanvasQrcode = (canvas, val) => {
    QRCode.toCanvas(canvas, val, {
        errorCorrectionLevel: 'L',
        margin: 1,
        width: 220,
    }, function(err) {
        if (err) console.error('生成二维码出错', err);
        console.log('二维码生成成功');
    });
};

/**
 * 比较两个时间的大小，返回是否第一个时间大于第二个时间
 * @param {Date} aTime 时间
 * @param {Date} bTime 时间
 */
export const compareTimeValue = (aTime, bTime) => {
    return dayjs(aTime) > dayjs(bTime);
};

/**
 * 比较时间去当前时间的大小，返回是否大于当前时间
 * @param {Date} time 时间
 */
export const compareTime = (time) => {
    return dayjs(time) > dayjs();
};

/**
 * 屏蔽安卓实体按键，防止误操作
 */
export const preventAndriodBack = () => {
    const { isWechatMini, isAlipayMini } = platformTruth();
    if (isWechatMini || isAlipayMini) {
        return;
    } else {
        let XBack = {};
        (function(XBack) {
            XBack.STATE = 'x - back';
            XBack.element;
            XBack.onPopState = function(event) {
                event.state === XBack.STATE && XBack.fire();
                XBack.record(XBack.STATE); //初始化事件时，push一下
            };
            XBack.record = function(state) {
                history.pushState(state, null, location.href);
            };
            XBack.fire = function() {
                var event = document.createEvent('Events');
                event.initEvent(XBack.STATE, false, false);
                XBack.element.dispatchEvent(event);
            };
            XBack.listen = function(listener) {
                XBack.element.addEventListener(XBack.STATE, listener, false);
            };
            XBack.init = function() {
                XBack.element = document.createElement('span');
                window.addEventListener('popstate', XBack.onPopState);
                XBack.record(XBack.STATE);
            };
        })(XBack); // 引入这段js文件
        XBack.init();
        XBack.listen(function() {});
    }
};

/**
 * 输入框键盘收起事件
 */
export const inputBlurAction = () => {
    document.activeElement.scrollIntoViewIfNeeded(true);
    setTimeout(() => {
        const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
        window.scrollTo(0, Math.max(scrollHeight - 1, 0));
    }, 100);
};

/**
 * 比较两个数组是否完全相同
 * @param {Array} arrOne 数组一
 * @param {Array} arrTwo 数组二
 */
export const compareArray = (arrOne, arrTwo) => {
    if (arrOne.length !== arrTwo.length) return false;
    let flag = true;
    for(let i = 0; i < arrTwo.length; i++) {
        if (arrOne[i] !== arrTwo[i]) {
            flag = false;
            break;
        }
    }
    return flag;
};

/**
 * 判断对象是否为空，并且所有元素为空
 * @param {Object} obj 对象
 */
export const isEmptyObject = (obj) => {
    let flag = true;
    for (let key in obj) {
        if (obj[key] !== '') {
            flag = false;
            break;
        }
    }
    return flag;
};
